﻿using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Filters;

namespace FeishuWorkflowService.Filters;

public class AsyncLoggingFilter : IAsyncActionFilter
{
    private readonly ILogger<AsyncLoggingFilter> _logger;

    public AsyncLoggingFilter(ILogger<AsyncLoggingFilter> logger)
    {
        _logger = logger;
    }

    public async Task OnActionExecutionAsync(
        ActionExecutingContext context,
        ActionExecutionDelegate next)
    {
        // 执行前逻辑（等同于 OnActionExecuting）
        var request = context.HttpContext.Request;
        var actionName = context.ActionDescriptor.DisplayName;
        var parameters = context.ActionArguments;

        _logger.LogInformation("Action开始执行: {ActionName}", actionName);
        _logger.LogInformation("请求路径: {Path}", request.Path);
        _logger.LogInformation("请求方法: {Method}", request.Method);
        
        if (parameters.Any())
        {
            _logger.LogInformation("请求参数: {Parameters}", 
                JsonSerializer.Serialize(parameters, new JsonSerializerOptions 
                { 
                    MaxDepth = 16,
                    IgnoreReadOnlyProperties = true,
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                }));
        }

        var stopwatch = System.Diagnostics.Stopwatch.StartNew();

        // 执行 Action 并等待结果（关键区别点）
        ActionExecutedContext executedContext = await next();

        stopwatch.Stop();

        // 执行后逻辑（等同于 OnActionExecuted）
        _logger.LogInformation("完成执行 Action: {ActionName}, 耗时: {ElapsedMs}ms",
            context.ActionDescriptor.DisplayName,
            stopwatch.ElapsedMilliseconds);
    }
}